package com.matol.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.matol.entity.User;
import com.matol.service.UserService;
import com.matol.util.JiaJie;
import com.matol.util.Tools;

/** 
 *  
 * @author matol 
 * @date 2013-01-23 16:38 
 */  
@Controller  
@RequestMapping(value = "/user")  
public class UserController {  
  
	@Resource(name = "userServiceImpl")
	private UserService userService;
	@Resource  
    private Validator validator; 

	/** 
     * @author matol 
     * @date 2013-01-23 16:38 
     * @return 
     */  
    @RequestMapping(value = "/list")  
    public ModelAndView getAllUser(HttpServletRequest request,HttpServletResponse response) throws Exception {  
    	Map<String, Object> map = new HashMap<String, Object>();
    	
    	List<User> result = new ArrayList<User>();
    	result = userService.findAll();
		 
		map.put("result", result);
		return new ModelAndView("/user/list", map);
    } 
	/** 
     * @author matol 
     * @date 2013-01-23 16:38 
     * @return 
     */  
    @RequestMapping(value = "/list/{id}")  
    public ModelAndView getTheUser(@PathVariable("id") int id){  
    	Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", userService.findById(id));
		
		return new ModelAndView("/user/adds", map);
    }     
    
    
    @RequestMapping(value = "/toAdd")  
    public ModelAndView toAddUser(){  
    	Map<String, Object> map = new HashMap<String, Object>();
    	//map.put("user", new User());
		
		return new ModelAndView("/user/adds", map);
    }
    @RequestMapping(value = "/doAdd")  
    public String addUser(@ModelAttribute("user") User user,BindingResult result,RedirectAttributes redirectAttributes,HttpSession httpSession){ 
    	try {
			this.validator.validate(user, result);//添加验证  
			if (result.hasErrors()) {  
			    redirectAttributes.addFlashAttribute("message", "新增失败，请检查数据合理性");
				List<ObjectError> ls=result.getAllErrors();
	            for (int i = 0; i < ls.size(); i++) {
	            	redirectAttributes.addFlashAttribute(ls.get(i).getCode(), ls.get(i).getDefaultMessage());
	                //System.out.println("error:"+ls.get(i).getCode()+": "+ls.get(i).getDefaultMessage());
	            }
	            redirectAttributes.addFlashAttribute("user", user);
	            
				return "redirect:/user/toAdd";	 
			} 
			
			Integer id = 0;
			if(user != null){
				if(user.getId() ==null || user.getId().equals(0)){
					user.setPass(JiaJie.jia(user.getPass(), "matol", ""));
					userService.create(user);
					id = user.getId();
					
					//保存登陆状态
					httpSession.setAttribute("loginedUser", user);
					httpSession.setAttribute("name", user.getName());
					
					redirectAttributes.addFlashAttribute("message", "新增成功");
				}else{
					id = userService.modify(user);
					redirectAttributes.addFlashAttribute("message", "修改成功");
				}
			}
			
			//System.out.println("##["+id+"]");
			
			if(id != null && id != 0){
				Map<String, Object> map = new HashMap<String, Object>();
				
				List<User> rs = new ArrayList<User>();
				rs = userService.findAll();
				
				map.put("result", rs);
			}
    	} catch (Exception e) { Tools.Logs("##[addUser]##"+e.getMessage()); } 
    	
    	return "redirect:list";	
    } 
    

    @RequestMapping(value = "/toLogin")  
    public ModelAndView toLogin(){ 
		return new ModelAndView("/user/login", null);
    }    
    @RequestMapping(value = "/outLogin")  
    public String outLogin(HttpSession httpSession){ 
    	//注销登陆状态
    	httpSession.setAttribute("loginedUser", null);
    	httpSession.setAttribute("name", null);
    	
    	return "redirect:/user/toLogin";
    }    
    @RequestMapping(value = "/doLogin")  
    public String doLogin(@ModelAttribute("user") User user,BindingResult result,RedirectAttributes redirectAttributes,HttpSession httpSession){ 
    	user.setAge(50);//默认严重通过
    	this.validator.validate(user, result);//添加验证  
		if(result.hasErrors()) {  
		    //redirectAttributes.addFlashAttribute("message", "登陆失败，请检查数据合理性");
			List<ObjectError> ls=result.getAllErrors();
            for (int i = 0; i < ls.size(); i++) {
            	redirectAttributes.addFlashAttribute(ls.get(i).getCode(), ls.get(i).getDefaultMessage());
            }
            redirectAttributes.addFlashAttribute("user", user);
            
			return "redirect:/user/toLogin";	 
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			List<User> rs = new ArrayList<User>();
			
			user.setPass(JiaJie.jia(user.getPass(), "matol", ""));
			
			User u = userService.findByUser(user);
			if(u != null){
				rs = userService.findAll();
				map.put("result", rs);
				
				//保存登陆状态
				httpSession.setAttribute("loginedUser", u);
				httpSession.setAttribute("name", u.getName());
				
				return "redirect:list";	
			}else{
				redirectAttributes.addFlashAttribute("message", "登陆失败，用户名或密码错误");
				return "redirect:/user/toLogin";
			}
		}
    }
  
	/** 
     * @author matol 
     * @date 2013-01-23 16:38
     * @return 
     */  
    @RequestMapping(value = "/delete/{id}")  
    public String deleteTheUser(@PathVariable("id") int id,RedirectAttributes redirectAttributes){  
    	Map<String, Object> map = new HashMap<String, Object>();
    	
    	userService.delete(id);
    	
    	List<User> result = new ArrayList<User>();
    	result = userService.findAll();
		map.put("result", result);
		redirectAttributes.addFlashAttribute("message", "删除成功");
		
		return "redirect:/user/list";
    }     
    
}  